<template>
  <van-form @submit="loginSubmit" class="mt-8" :disabled="timer">
    <van-cell-group inset>
      <van-field
        v-model="form.type"
        is-link
        readonly
        label="模式"
        @click="showPicker = true"
      />
      <van-field
        v-model="form.loseMaxMoney"
        label="最大输量"
        :rules="[
          { required: true, message: '请填写最大输量(输多少自动停止脚本)' },
        ]"
      />
      <van-field name="slider" label="起始妖精">
        <template #input>
          <van-slider
            v-model="form.baseMoney"
            :min="500"
            :max="10000"
            :step="100"
            active-color="#ee0a24"
          >
            <template #button>
              <div class="custom-button">{{ form.baseMoney }}</div>
            </template>
          </van-slider>
        </template>
      </van-field>
      <van-field
        v-model="form.logname"
        name="用户名"
        label="用户名"
        placeholder="妖火号/手机号"
        :rules="[{ required: true, message: '请填写用户名' }]"
      />
      <van-field
        v-model="form.logpass"
        type="password"
        name="密码"
        label="密码"
        placeholder="密码"
        :rules="[{ required: true, message: '请填写密码' }]"
      />
    </van-cell-group>
    <div style="margin: 16px">
      <van-button
        class="rounded-md"
        block
        type="primary"
        native-type="submit"
        :disabled="timer"
        >开始</van-button
      >
    </div>
  </van-form>
  <div class="tips">本次参数可连输{{ maxLoseCount }}次</div>
  <van-popup v-model:show="showPicker" position="bottom">
    <van-picker
      :columns="columns"
      value-key="label"
      @confirm="onConfirm"
      @cancel="showPicker = false"
    />
  </van-popup>

  <div class="flex justify-center">
    <van-badge :content="form.userMoney" v-show="form.userMoney">
      <van-image width="35" height="40" :src="getSrc('../assets/dlam.gif')" />
      <van-image width="35" height="40" :src="getSrc('../assets/cs.gif')" />
      <van-image width="30" height="40" :src="getSrc('../assets/pkq.gif')" />
    </van-badge>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue';
import { Toast } from 'vant';
import { login, postGame, getMyGameList, getUserInfo } from '@/api/common';
import Cookies from 'js-cookie';
const showPicker = ref(false);
const columns = [
  {
    label: '稳定型(倍率80%)',
    value: 1.8,
  },
  {
    label: '激进型(倍率200%)',
    value: 2,
  },
  {
    label: '赌狗模式(倍率300%)',
    value: 3,
  },
];
const gameCount = ref(0);
const form = reactive({
  type: '稳定型(倍率80%)',
  loseMaxMoney: 1500,
  baseMoney: 500,
  logname: '',
  logpass: '',
  userId: '',
  userMoney: '',
});
// 倍投金额
let betMoney = 0;
// 盈利妖精
let winMoney = 0;
let currentLostCount = 0;
let timer = ref(null);
const onConfirm = (value) => {
  form.type = value.label;
  showPicker.value = false;
};
const getSrc = (url) => {
  return new URL(url, import.meta.url).href;
};
// 登录
const loginSubmit = () => {
  const loginParams = {
    logname: form.logname,
    logpass: form.logpass,
    action: 'login',
  };
  login(loginParams).then((res) => {
    if (res.indexOf('登录成功') > 0) {
      Toast.success('登录成功,游戏将于5秒后开始');
      betMoney = form.baseMoney;
      console.log('第一次金额', betMoney);
      winMoney = 0;
      timer.value = setInterval(getGameList, 5000);
      // getGameList();
    } else {
      Toast.fail('请确认密码正确');
    }
  });
};
// 添加游戏
const addGame = () => {
  let gameParams = {
    mymoney: parseInt(betMoney),
    question: '爱生活还是爱妖火?',
    answer1: '爱生活',
    answer2: '爱妖火',
    myanswer: (Math.floor(Math.random() * 10) % 2) + 1,
    action: 'gomod',
    classid: 194,
    siteid: 1000,
    sid: Cookies.get('sidyaohuo'),
    bt: '确 定',
  };
  const date = new Date();
  postGame(gameParams).then((res) => {
    if (res.indexOf('请输入您的密码') > 0) {
      gameParams = {
        needpassword: form.logpass,
        siteid: 1000,
        classid: 194,
        sid: Cookies.get('sidyaohuo'),
        go: '确定',
      };
      postGame(gameParams).then(() => {
        console.log('验证开始');
        addGame();
      });
    } else {
      gameCount.value++;
      console.log(
        `${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}创建游戏成功,本次答案为${
          gameParams.myanswer
        }`
      );
      console.log(`您今日已吹牛${gameCount.value}次,战果:${winMoney}妖精`);
    }
  });
};
// 查询历史列表
const getGameList = async () => {
  // 获取我的妖精
  await getUserInfo().then((res) => {
    form.userMoney = res.substring(
      res.indexOf('我的妖晶') + 5,
      res.indexOf('<', res.indexOf('我的妖晶'))
    );
    form.userId = res.substring(
      res.indexOf('我的ID: ') + 6,
      res.indexOf('<img src="/bbs/medal')
    );
  });
  const listParams = {
    type: 0,
    touserid: form.userId,
    siteid: 1000,
    classid: 194,
  };
  getMyGameList(listParams).then((res) => {
    const firIndex = res.indexOf('<div class="line1">');
    const secIndex = res.indexOf('</div><div class="line2">');
    const msg = res.substring(firIndex + 19, secIndex);
    if (msg.indexOf('进行') > 0) {
      console.log('暂无赌狗在线');
      return;
    }
    if (gameCount.value > 0) {
      if (msg.indexOf('赚') > 0) {
        currentLostCount = 0;
        betMoney = form.baseMoney;
        winMoney += parseInt(
          parseInt(msg.substring(msg.indexOf('赚了') + 2, msg.indexOf('(包'))) *
            0.9
        );
      } else {
        currentLostCount++;
        betMoney *= parseFloat(
          columns.find((item) => item.label === form.type).value
        );
        winMoney -= parseInt(
          msg.substring(msg.indexOf('输了') + 2, msg.indexOf('个妖'))
        );
      }
    }
    if (currentLostCount === maxLoseCount.value) {
      clearInterval(timer.value);
      timer.value = null;
      console.log(
        `当前已连输${maxLoseCount.value}次,脚本已自动停止,如需继续请手动开启`
      );
      return;
    }
    addGame();
  });
};
const maxLoseCount = computed(() => {
  let count = 0;
  let money = form.baseMoney;
  const bet = parseFloat(
    columns.find((item) => item.label === form.type).value
  );
  while (money <= form.loseMaxMoney) {
    count++;
    money *= bet;
  }
  return count;
});
</script>

<style scoped>
.custom-button {
  padding: 5px;
  color: #fff;
  font-size: 10px;
  line-height: 15px;
  text-align: center;
  background-color: #4fc08d;
  border-radius: 100px;
}

.main {
  padding-top: 25px;
}
.van-cell-group {
  background-color: rgba(255, 255, 255, 0.7);
}
.van-cell {
  background-color: rgba(255, 255, 255, 0);
}
.van-button {
  background-color: rgba(251, 114, 153, 0.7);
  border: rgba(0, 0, 0, 0);
  font-size: 16px;
}
.tips {
  background: #4fc08d;
  color: white;
  border-radius: 8px;
  height: 24px;
  line-height: 24px;
  text-align: center;
  width: 92%;
  font-size: 14px;
  margin: 0 auto 20px;
}
</style>
